package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.uitls.MD5Util;
import com.example.forum.uitls.StringUtil;
import com.example.forum.uitls.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public void createNormalUser(User user) {
        if(user==null||StringUtil.isEmpty(user.getUsername())
                ||StringUtil.isEmpty(user.getNickname())
                ||StringUtil.isEmpty(user.getPassword())
                ||StringUtil.isEmpty(user.getSalt())){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User exists=selectByUserName(user.getUsername());
        if(exists!=null){
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
        }
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row=userMapper.insertSelective(user);
        if(row!=1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        log.info("新增成功：username="+user.getUsername());
    }

    @Override
    public User login(String username, String password) {
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user=selectByUserName(username);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if(!MD5Util.decryptPassword(password,user.getSalt(),user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }
        log.info("登陆成功");
        return user;
    }

    @Override
    public User selectById(Long id) {
        if(id==null||id<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        User user=selectById(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        User user=selectById(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if(user==null||user.getId()==null||user.getId()<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User existsUser=userMapper.selectByPrimaryKey(user.getId());
        if(existsUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        User updateUser=new User();
        updateUser.setId(user.getId());
        boolean checkAttr=false;

        if(!StringUtil.isEmpty(user.getUsername())
                &&!user.getUsername().equals(existsUser.getUsername())){
            User checkUser=userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr=true;
        }

        if(!StringUtil.isEmpty(user.getNickname())
                &&!user.getNickname().equals(existsUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }

        if(user.getGender()!=null
                &&!user.getGender().equals(existsUser.getGender())){
            user.setGender(updateUser.getGender());
            if(user.getGender()>2||user.getGender()<0){
                user.setGender((byte) 2);
            }
            checkAttr=true;
        }

        if(!StringUtil.isEmpty(user.getEmail())
                &&!user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }

        if(!StringUtil.isEmpty(user.getPhoneNum())
                &&!user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }

        if(!StringUtil.isEmpty(user.getRemark())
                &&!user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }

        if(!checkAttr){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    public void modifyPassword(Long id,String newPassword,String oldPassword){
        if(id==null||id<=0||StringUtil.isEmpty(newPassword)||StringUtil.isEmpty(oldPassword)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User user=userMapper.selectByPrimaryKey(id);
        if(user==null||user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        String salt=user.getSalt();
        String encryptPassword=MD5Util.md5Salt(oldPassword,salt);
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }

        salt=UUIDUtil.UUID_32();
        encryptPassword=MD5Util.md5Salt(newPassword,salt);
        User updateUser=new User();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }


}
